package com.xie.smfs.item;

import com.xie.smfs.registry.ModEffects;
import com.xie.smfs.registry.ModSounds;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.MusicDiscItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.ActionResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Box;
import net.minecraft.world.World;
import java.util.List;

public class GhostRecordItem extends MusicDiscItem {
    private static final int EFFECT_DURATION = 3600; // 6 分钟，3600 刻
    private static final double EFFECT_RADIUS = 16.0; // 影响范围半径

    public GhostRecordItem(Settings settings) {
        // 确保使用正确的音效
        super(15, SoundEvents.ENTITY_ZOMBIE_ATTACK_WOODEN_DOOR, settings, 60);
    }

    @Override
    public ActionResult useOnBlock(ItemUsageContext context) {
        World world = context.getWorld();
        BlockPos pos = context.getBlockPos();
        ItemStack stack = context.getStack();
        PlayerEntity player = context.getPlayer();

        // 首先检查是否在客户端
        if (world.isClient) {
            return ActionResult.SUCCESS; // 在客户端只返回成功
        }

        // 检查是否放置在音符盒上
        if (!world.getBlockState(pos).getBlock().equals(net.minecraft.block.Blocks.JUKEBOX)) {
            return ActionResult.PASS; // 如果不是放在音符盒上，则跳过
        }

        // 手动处理唱片播放逻辑
        // 播放音效
        world.playSound(null, pos, this.getSound(), SoundCategory.RECORDS, 6.0F, 1.0F);

        // 给周围玩家添加效果
        applyEffectToNearbyPlayers(world, pos);

        // 消耗物品
        if (player != null && !player.getAbilities().creativeMode) {
            stack.decrement(1);
        }

        return ActionResult.SUCCESS;

    }

    private void applyEffectToNearbyPlayers(World world, BlockPos pos) {
        // 使用 Box 类创建以 BlockPos 为中心的包围盒
        Box box = new Box(
                pos.getX() - EFFECT_RADIUS, pos.getY() - EFFECT_RADIUS, pos.getZ() - EFFECT_RADIUS,
                pos.getX() + EFFECT_RADIUS, pos.getY() + EFFECT_RADIUS, pos.getZ() + EFFECT_RADIUS
        );
        List<PlayerEntity> players = world.getNonSpectatingEntities(PlayerEntity.class, box);
        for (PlayerEntity player : players) {
            player.addStatusEffect(new StatusEffectInstance(ModEffects.KNOCKING_CURSE, EFFECT_DURATION, 0));
        }
    }
}